package yicheng.dinnertogetherapp;

import java.util.HashMap;
import java.util.List;











import yicheng.dinnertogetherapp.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

public class SearchFriendListActivity extends Activity {
	ListView searchFriend_list_listView;
	LinearLayout searchFriend_loading_layout, sendFriendRequest_loading_layout;

	List<String> domainNames;

	AmazonClientManager clientManager;

	SharedPreferences local_user_information;
	SharedPreferences.Editor local_user_editor;
	String PREFS_NAME = "LocalUserInfo";


	String SEARCHED_PHONE_NUMBER;
	String SEARCHED_NICKNAME;
	String PHONE_NUMBER;
	String NICKNAME;

	HashMap<String, String> myFriendList;
	Handler handler;

	ArrayAdapter<String> adapter;

	boolean isDataBaseLoaded = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		clientManager = new AmazonClientManager();

		local_user_information =  this.getSharedPreferences(PREFS_NAME,0);

		Intent intent = getIntent();
		Bundle registerInfoData = intent.getBundleExtra("SearchedUserInformation");
		SEARCHED_PHONE_NUMBER = registerInfoData.getString("SerachedPhoneNumber");

		setContentView(R.layout.search_friend_list_view);
		overridePendingTransition(R.anim.activity_left_in,R.anim.activity_left_out);

		searchFriend_loading_layout = (LinearLayout) findViewById(R.id.search_friend_loading_view_layout);

		sendFriendRequest_loading_layout = (LinearLayout) findViewById(R.id.sendFriendRequest_loading_view_layout);
		sendFriendRequest_loading_layout.setVisibility(View.INVISIBLE);

		if (isConnectedToInternet()){
			//load in database domain names
			new loadDataBase().execute();

		}
		else{
			Toast.makeText(getApplicationContext(), "You are not conneceted to Internet, please check.", Toast.LENGTH_SHORT).show();
		}







		handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				if (msg.what == 1){

					//set true when database is loaded 
					isDataBaseLoaded = true;
					if (isDataBaseLoaded){
						loadSearchedFriendList();
					}

					//set loading spinner invisble when database is loaded
					if (isDataBaseLoaded){
						searchFriend_loading_layout.setVisibility(View.INVISIBLE);
					}

				}
				if(msg.what == 2){


					searchFriend_list_listView = (ListView) findViewById(R.id.searchFriend_list_listView);

					String[] values = new String[] {SEARCHED_NICKNAME};
					adapter = new ArrayAdapter<String>(SearchFriendListActivity.this,
							R.layout.list_view_layout, R.id.listView_item_textView, values);
					searchFriend_list_listView.setAdapter(adapter);

					searchFriend_list_listView.setOnItemClickListener(new ListView.OnItemClickListener(){

						@Override
						public void onItemClick(AdapterView<?> parent,
								View view, int position, long id) {
							// TODO Auto-generated method stub

							if (myFriendList.containsKey(SEARCHED_PHONE_NUMBER)){
								Toast.makeText(getApplicationContext(), "The number is already your friend!", Toast.LENGTH_SHORT).show();
							}

							if (SEARCHED_PHONE_NUMBER.equals(PHONE_NUMBER)){
								Toast.makeText(getApplicationContext(), "You cannot add yourself as your friend!", Toast.LENGTH_SHORT).show();
							}

							if (!myFriendList.containsKey(SEARCHED_PHONE_NUMBER) && !SEARCHED_PHONE_NUMBER.equals(PHONE_NUMBER)){

								AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(SearchFriendListActivity.this);
								dialogBuilder.setTitle("Add Friend");
								dialogBuilder.setMessage("Send a friend request?");
								dialogBuilder.setCancelable(true);
								dialogBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() {

									@Override
									public void onClick(DialogInterface dialog, int which)  {
										// TODO Auto-generated method stub
										if (isConnectedToInternet()){

											sendFriendRequest_loading_layout.setVisibility(View.INVISIBLE);



											sendFriendRequest();
											dialog.cancel();

										}
										else{
											Toast.makeText(getApplicationContext(), "You are not conneceted to Internet, please check.", Toast.LENGTH_SHORT).show();
											dialog.cancel();	
										}


									}
								});



								dialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

									@Override
									public void onClick(DialogInterface dialog, int which)  {
										// TODO Auto-generated method stub
										dialog.cancel();
									}
								});

								AlertDialog dialog = dialogBuilder.create();
								dialog.show();




							}





						}

					});


				}

				if(msg.what == 3){
					sendFriendRequest_loading_layout.setVisibility(View.INVISIBLE);
					Toast.makeText(getApplicationContext(), "Friend request sent successfully", Toast.LENGTH_SHORT).show();
					finish();

				}

				if (msg.what == 4){

					AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(SearchFriendListActivity.this);
					dialogBuilder.setTitle("Add Friend");
					dialogBuilder.setMessage("The friend you searched has already sent you a request, do you want to see your request?");
					dialogBuilder.setCancelable(true);
					dialogBuilder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which)  {
							// TODO Auto-generated method stub
							Intent gotoFriendRequestListIntent = new Intent("yicheng.dinnertogetherapp.FRIENDREQUESTLISTACTIVITY");
							startActivity(gotoFriendRequestListIntent);

						}
					});



					dialogBuilder.setNegativeButton("No", new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which)  {
							// TODO Auto-generated method stub
							dialog.cancel();
						}
					});

					AlertDialog dialog = dialogBuilder.create();
					dialog.show();
				}



			}
		};






	}


	private void loadSearchedFriendList(){

		PHONE_NUMBER = local_user_information.getString("PhoneNumber", "default");
		if (domainNames.contains(SEARCHED_PHONE_NUMBER)){
			runOnUiThread(new Runnable(){

				@Override
				public void run() {
					// TODO Auto-generated method stub
					new Thread(new Runnable(){

						@Override
						public void run() {
							// TODO Auto-generated method stub
							SEARCHED_NICKNAME = SimpleDB.getSingleAttributesForItem(clientManager, SEARCHED_PHONE_NUMBER,SimpleDB.NICKNAME_ITEM, SimpleDB.NICKNAME_ATTRIBUTE);

							myFriendList = SimpleDB.getAttributesForItem(clientManager, PHONE_NUMBER, SimpleDB.FRIEND_LIST_ITEM);


							Message msg = Message.obtain();
							msg.what = 2;
							handler.sendMessage(msg);
						}

					}).start();
				}

			});





		}
		else{
			Toast.makeText(getApplicationContext(), "The phone number you searched is not registered.", Toast.LENGTH_SHORT).show();
		}



	}



	private class loadDataBase extends AsyncTask<Void, Void, Void> {

		@Override
		protected Void doInBackground(Void... Void) {
			// TODO Auto-generated method stu
			/*loadingSpinner.setVisibility(View.VISIBLE);*/
			domainNames = SimpleDB.getDomainNames(clientManager);


			//loadingSpinner.setVisibility(View.VISIBLE);


			/*	}
			catch (NullPointerException e){
				Toast.makeText(getApplicationContext(), "Your connection to Internet has problem, please check.", Toast.LENGTH_SHORT).show();
			}*/
			Message msg = Message.obtain();
			msg.what = 1;
			handler.sendMessage(msg);
			//return null;
			return null;
		}
	}



	private boolean isConnectedToInternet(){
		ConnectivityManager connectivityManager = 
				(ConnectivityManager)SearchFriendListActivity.this.getSystemService(Context.CONNECTIVITY_SERVICE);

		NetworkInfo wifi_network = 
				connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
		NetworkInfo mobile_network = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);


		return wifi_network.isConnectedOrConnecting() || mobile_network.isConnectedOrConnecting();
	}


	private void sendFriendRequest(){
		local_user_information =  this.getSharedPreferences(PREFS_NAME,0);
		PHONE_NUMBER = local_user_information.getString("PhoneNumber", "default");
		NICKNAME = local_user_information.getString("Nickname", "default");

		runOnUiThread(new Runnable(){

			@Override
			public void run() {
				// TODO Auto-generated method stub
				new Thread(new Runnable(){

					@Override
					public void run() {
						// TODO Auto-generated method stub

						HashMap<String, String> myFriendRequestList = SimpleDB.getAttributesForItem(clientManager, PHONE_NUMBER, SimpleDB.FRIEND_REQUEST_LIST_ITEM);

						if (myFriendRequestList.containsKey(SEARCHED_PHONE_NUMBER)){
							Message msg = Message.obtain();
							msg.what = 4;
							handler.sendMessage(msg);
						}
						else{

							HashMap<String, String> searchedFriendFriendRequestList = SimpleDB.getAttributesForItem(clientManager, SEARCHED_PHONE_NUMBER, SimpleDB.FRIEND_REQUEST_LIST_ITEM);

							searchedFriendFriendRequestList.put(PHONE_NUMBER, NICKNAME);

							SimpleDB.updateAttributesForItem(clientManager, SEARCHED_PHONE_NUMBER,  SimpleDB.FRIEND_REQUEST_LIST_ITEM, searchedFriendFriendRequestList);

							Message msg = Message.obtain();
							msg.what = 3;
							handler.sendMessage(msg);

						}




					}

				}).start();
			}

		});
	}










}
